package com.tanhua.dubbo.api;


import com.tanhua.mongo.RecommendUser;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService
public class RecommendUserApiImpl implements RecommendUserApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //创建一个Criteria对象,构造查询条件
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //根据Criteria创建Query对象
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .limit(1);
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageResult queryRecommendUserList(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Query query = new Query(criteria);
        int count = (int) mongoTemplate.count(query, RecommendUser.class);
        query.skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("score")));
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        PageResult pr = new PageResult(page,pagesize,count,recommendUsers);
        return pr;
    }
}
